<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/4
 * Time: 13:06
 */

namespace app\admin\controller;



use app\admin\lib\AdminController;
use app\common\controller\Files;
use app\common\model\DynamicFlow;
use app\common\model\teacher\TeacherEssay;
use app\common\model\teacher\TeacherEssayCatalog;
use app\admin\model\ApiResponse;
use think\Db;


class Essays extends AdminController
{
    /**
     * 资讯列表
     *
     * @return \app\admin\model\PageResponse
     */
    public function list() {

        $form = $this->getAndCheckForm([
            ['limit', 'require|^\\d+$'],
            ['offset', 'require|^\\d+$'],
            ['catalog_id', 'integer'],
            ['teacher_id', 'integer'],
            ['column_id', 'integer'],
        ]);

        $teacher_id = $form['teacher_id'] ?? -1;
        return TeacherEssay::manageList(intval($form['limit']), intval($form['offset']),
            $form['catalog_id'],$teacher_id,$form['keywords']??null,$form['column_id']??-1);
    }

    /**
     * 资讯添加和修改
     *
     * @return ApiResponse
     */
    public function save() {

        Db::transaction(function () {
            $form = $this->getAndCheckForm([
                ['teacher_id', 'require|integer',],
                ['content', 'require'],
                ['category', 'require|^\\d+$'],
            ]);

            $isNew = false;
            if (isset($form['id'])) {
                $model = TeacherEssay::get($form['id']);
            }
            if (empty($model)) {
                $isNew = true;
                $model = new TeacherEssay();
            }

            // 自动下载内容中的远程图片并同步到oss
            if (isset($form['content'])) $form['content'] = Files::imgSync($form['content']);

            // 绑定股票代码 wxj
            if(isset($form['stocks'])){
                foreach ($form['stocks'] as $k=>$v){
                    $form['stocks'][$k]=strtolower($v);
                }
                $form['stocks']=json_encode($form['stocks']);
            }

            // 绑定课程 zk20180525
            if (isset($form['bind_course'])) {
                // 转换json中有string类型数字为int类型数字
                $bind_course = json_decode(json_encode($form['bind_course'], JSON_UNESCAPED_UNICODE));
                foreach ($bind_course as &$bindCourseVal) {
                    if (is_numeric($bindCourseVal)) $bindCourseVal = intval($bindCourseVal);
                }
                $form['bind_course'] = json_encode($bind_course, JSON_UNESCAPED_UNICODE);
            }

            // 随机点赞数
            $form['num_liked'] = rand(19, 69);

            $model->data($form);
            $model->save();

            TeacherEssay::articleUpdatePushMsg($model->id);

            if ($model->teacher_id && $isNew) $model->makeDynamicData($isNew,DynamicFlow::SOURCE_ADMIN);

        });
        return ApiResponse::success();
    }

    /**
     * 资讯删除
     * @return ApiResponse
     */
    public function del() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);
        $id = intval($form['id']);
        if ($id > 0) {
            TeacherEssay::del($id);
        }

        return ApiResponse::success();
    }

    /**
     * 资讯隐藏
     *
     * @return ApiResponse
     */
    public function hide() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['hide', 'require|integer',],
        ]);
        $id = intval($form['id']);

        TeacherEssay::setHide($id, (1 == $form['hide']));

        TeacherEssay::articleUpdatePushMsg($id);

        return ApiResponse::success();
    }

    /**
     * 资讯设置推荐
     *
     * @return ApiResponse
     */
    public function recommend() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['recommend', 'require|integer',],
        ]);

        TeacherEssay::update([
            'id' => intval($form['id']),
            'recommend' => (1 == $form['recommend']),
        ]);

        return ApiResponse::success();
    }

    /**
     * 资讯分类列表
     *
     * @return mixed
     */
    public function catalog_list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $result = TeacherEssayCatalog::manageList(intval($form['page']??1),intval(100));

        $result['code'] = 200;
        return $result;
    }

    /**
     * 资讯分类保存
     *
     * @return ApiResponse
     */
    public function catalog_save() {
        $form = $this->getAndCheckForm([
            ['id', 'integer',],
        ]);

        if (isset($form['id'])) {
            if(isset($form['parent_id']) && $form['parent_id']>0){
                if($form['id']==$form['parent_id']) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'不能选择自己作为父级目录');
                if(!TeacherEssayCatalog::findById($form['parent_id'])) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'所选父级目录不存在');
            }
            TeacherEssayCatalog::update($form, [], TeacherEssayCatalog::getSaveFields());
        } else {
            TeacherEssayCatalog::create($form, TeacherEssayCatalog::getSaveFields());
        }

        return ApiResponse::success();
    }

    /**
     * 资讯分类删除
     *
     * @return ApiResponse
     */
    public function catalog_del() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);

        $exists=TeacherEssayCatalog::findByParentId($form['id']);
        if($exists) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'请先删除分支');

        $re = TeacherEssayCatalog::checkUsed($form['id']);
        if ($re) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'使用中不能删除');

        TeacherEssayCatalog::destroy($form['id']);

        return ApiResponse::success();
    }

    public function branch(){
        return ApiResponse::success(TeacherEssayCatalog::getBranch());
    }

}